<template>
    <ul
        class="ea-menu w-full min-h-[400px] text-lg"
        :class="props.mode === 'folding' ? 'ea-menu--folding' : 'ea-menu--unfolding'"
    >
        <slot />
    </ul>
</template>
<script lang="ts" setup>
import { provide, ref, watch } from 'vue'

interface Props {
    defaultActive?: string
    mode?: 'folding' | 'unfolding'
    uniqueOpened?: boolean
    /** 菜单路由数据，用于查找激活路由对应的父菜单 */
    menuRoutes?: Array<{
        path: string
        children?: Array<{
            path: string
            meta: {
                activeRoute: string
                hidden?: boolean
            }
        }>
        meta: {
            activeRoute: string
            hidden?: boolean
        }
    }>
}
const props = withDefaults(defineProps<Props>(), {
    defaultActive: '',
    mode: 'folding',
    uniqueOpened: false,
    menuRoutes: () => [],
})
const activeIndex = ref<string>(props.defaultActive)
const openedSubMenus = ref<Set<string>>(new Set())

// 根据激活路由找出应该展开的父菜单
const findParentMenuForActiveRoute = (activeRoute: string): string | null => {
    if (!props.menuRoutes || !activeRoute) return null

    for (const menuRoute of props.menuRoutes) {
        if (menuRoute.children && menuRoute.children.length > 0) {
            for (const child of menuRoute.children) {
                if (!child.meta.hidden && child.meta.activeRoute === activeRoute) {
                    return menuRoute.path
                }
            }
        }
    }
    return null
}

// 设置默认展开的子菜单
const setDefaultOpenedSubMenus = (activeRoute: string) => {
    if (props.mode !== 'unfolding' || !activeRoute) return

    const parentMenuRoute = findParentMenuForActiveRoute(activeRoute)

    if (parentMenuRoute) {
        if (props.uniqueOpened) {
            // 唯一展开模式：清空其他，只展开当前
            openedSubMenus.value.clear()
            openedSubMenus.value.add(parentMenuRoute)
        } else {
            // 普通模式：添加当前
            openedSubMenus.value.add(parentMenuRoute)
        }
    }
}

watch(
    () => props.defaultActive,
    (newVal) => {
        activeIndex.value = newVal
        setDefaultOpenedSubMenus(newVal)
    },
    { immediate: true },
)

// 子菜单开关控制函数
const toggleSubMenu = (subMenuId: string) => {
    if (props.uniqueOpened) {
        // 如果启用唯一开启模式，先关闭其他所有子菜单
        if (openedSubMenus.value.has(subMenuId)) {
            openedSubMenus.value.delete(subMenuId)
        } else {
            openedSubMenus.value.clear()
            openedSubMenus.value.add(subMenuId)
        }
    } else {
        // 正常模式，可以同时开启多个子菜单
        if (openedSubMenus.value.has(subMenuId)) {
            openedSubMenus.value.delete(subMenuId)
        } else {
            openedSubMenus.value.add(subMenuId)
        }
    }
}

provide('menuOptions', {
    activeIndex,
    mode: props.mode,
    uniqueOpened: props.uniqueOpened,
    openedSubMenus,
    toggleSubMenu,
})
</script>
<style lang="scss" scoped></style>
